package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jndi.JndiFactory;
import models.Camera;
import models.User;

public class CameraDaoImpl implements CameraDao {
	
	final JndiFactory jndi = JndiFactory.getInstance();
	final UserDao userDao = DaoFactory.getInstance().getUserDao();
	

	@Override
	public List<Camera> list(Long userId) {
		
		List<Camera> cameras = new ArrayList<>();
		Connection connection = null;
		User user = userDao.getUser(userId);
		String sqlStatement = "SELECT id, location, url FROM cameras WHERE id IN(" + user.getCameras() + ")";
		
	
		try {
			connection = jndi.getConnection("jdbc/waiDatenbank");
			
			PreparedStatement ps = connection.prepareStatement(sqlStatement);
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()) {
				Camera camera = new Camera();
				camera.setId(rs.getLong("id"));
				camera.setLocation(rs.getString("location"));
				camera.setUrl(rs.getString("url"));
				cameras.add(camera);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JndiFactory.closeConnection(connection);
		}
		
		
		return cameras;
	}


	@Override
	public List<Camera> listAll() {
		
		List<Camera> cameras = new ArrayList<>();
		Connection connection = null;
	
		try {
			connection = jndi.getConnection("jdbc/waiDatenbank");
			
			PreparedStatement ps = connection.prepareStatement("SELECT id, location, url FROM cameras");
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()) {
				Camera camera = new Camera();
				camera.setId(rs.getLong("id"));
				camera.setLocation(rs.getString("location"));
				camera.setUrl(rs.getString("url"));
				cameras.add(camera);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JndiFactory.closeConnection(connection);
		}
		
		
		return cameras;
	}


	@Override
	public Camera getCamera(Long camId) {
		
		Camera camera = null;
		Connection connection = null;

		try {
			connection = jndi.getConnection("jdbc/waiDatenbank");

			PreparedStatement ps = connection
					.prepareStatement("SELECT id, location, url FROM cameras WHERE id=?");
			ps.setLong(1, camId);
			ResultSet rs = ps.executeQuery();

			if(rs.next()) {
				camera = new Camera();
				camera.setId(rs.getLong("id"));
				camera.setLocation(rs.getString("location"));
				camera.setUrl(rs.getString("url"));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JndiFactory.closeConnection(connection);
		}

		return camera;
	}

}
